import subprocess
import sys


def uninstall_all_packages():
    import importlib.metadata
    # 获取当前环境中的所有已安装库  list() 迭代器转换为列表,用于统计模块总数
    packages=list(importlib.metadata.distributions())
    if packages:
        for p in packages:
            """pip模块不卸载"""
            if p.name in ['pip']:
                continue
            # print(f'{p.name}=={p.version}')
            # print(f'pip uninstall -y {p.name}')
            #卸载
            try:
                subprocess.check_call([sys.executable, '-m', 'pip', 'uninstall', '-y', p.name])
            except subprocess.CalledProcessError as e:
                print(f'{p.name}=={p.version} 卸载失败')
        print('模块总数= %d ' % (len(packages)))
    else:
        print("当前没有任何库可供卸载。")

def uninstall_all_packages2():
    # 获取当前环境中的所有已安装库
    import pkg_resources
    for p in pkg_resources.working_set:
        """"""
        # print(f'pip uninstall -y {p.project_name}')
    print('包总数= %d ' % len(list(pkg_resources.working_set)))

if __name__ == "__main__":
    uninstall_all_packages()
    # uninstall_all_packages2()
    subprocess.check_call(['python', '--version'])
    subprocess.check_call(['pip', '--version'])
